
var shop="";
$(function () {
    /*保存*/
    $("#save").on("click", function () {
        $("#mapBox").css("display","none");
        $("#sys-goods-list").collapse('open')
        var dataObj={};
        $("#form input").each(function(index,dom){
            dataObj[$(dom).attr("name")]=$(dom).val();
        });
        dataObj["postType"] = $("#postType").val();
        if(shopId!==""){
            dataObj["id"]=shopId;
        }
        $.ajax({
            url: $api.shop[shop],
            type: "POST",
            dataType: "JSON",
            contentType : 'application/json',
            data: JSON.stringify(dataObj),
            beforeSend: function () {
                layerLoad = layer.load();
            },
            success: function (data) {
                layer.close(layerLoad);
                if(data.code == '111111'){
                    layer.msg(data.msg, {icon: 2});
                }else{
                    layer.msg(data.msg, {icon: 1});
                    $("#mapBox").css("display","none");
                    $("#form input").each(function(index,dom){
                        $(dom).val("");
                    });
                    Initialization();
                }
            },
            error: function () {
                layer.msg("网络开小差啦", {icon: 2});
            }
        });
    });
});

/*初始化*/
function Initialization(currentPage){
    $.ajax({
        url: $api.shop.selectShops,
        type: "POST",
        dataType: "JSON",
        data:JSON.stringify({"currentPage":currentPage == null ? 1 : currentPage}),
        contentType : 'application/json',
        beforeSend: function () {
            layerLoad = layer.load();
        },
        success: function (data) {
            //console.log(data);
            if(!$checkRemouteStatus(data)){
                layer.close(layerLoad);
                return;
            }
            layui.use('laytpl', function() {
                var laytpl = layui.laytpl;
                laytpl(sysOrderListTpl.innerHTML).render(data, function(html) {
                    $('#sys-order-list-body').html(html)
                });
            });
            layui.use('laypage', function() {
                layui.laypage({
                    cont: $('#sys-shop-list-body-page'),
                    pages: data.totalPage,
                    groups: 2,
                    curr: data.currentPage,
                    skip: true,
                    jump: function (obj,first) {
                        if(!first){
                            Initialization(obj.curr);
                        }
                    }
                });
            });
            layer.close(layerLoad);
        },
        error: function () {
            layer.msg("网络开小差啦", {icon: 2});
        }
    });
}
Initialization();

/*详情*/
var shopId="";
function edit(othis){
    $("#sys-goods-list").collapse('close');
    clearAll();
    $("#mapBox").css("display","block");
    shop="selectShopById";
    shopId=$(othis).attr("shopId");
    $.ajax({
        url: $api.shop[shop] + "?shopId=" + $(othis).attr("shopId"),
        type: "GET",
        dataType: "JSON",
        contentType : 'application/json',
        beforeSend: function () {
            layerLoad = layer.load();
        },
        success: function (data) {
            shop="updateShop";
            layer.close(layerLoad);
            var dataObj=data.msg;
            if(data.code == '111111'){
                layer.msg(data.msg, {icon: 2});
            }else{
                $("#name").val(dataObj.name);
                $("#intro").val(dataObj.intro);
                $("#nigtPrice").val(dataObj.nigtPrice);
                $("#dayPrice").val(dataObj.dayPrice);
                if(dataObj.postType == 3){
                	$("#postType").val("3");
                	//$("#postType option").eq(3).attr("selected",true);
                }
                if(dataObj.postType == 2){
                	$("#postType").val("2");
                	//$("#postType option").eq(2).attr("selected",true);
                }
                if(dataObj.postType == 1){
                	$("#postType").val("1");
                	//$("#postType option").eq(1).attr("selected",true);
                }
                if(dataObj.postType == 3){
                    $("#nigtPrice").parent().css("display","none");
                    $("#express").text("免运费金额");
                    $("#dayPrice").attr("placeholder","请输入免运费金额...");
                }else{
                    $("#nigtPrice").parent().css("display","block");
                    $("#express").text("白天费用");
                    $("#dayPrice").removeAttr("disabled");
                    $("#dayPrice").attr("placeholder","请输入白天费用...");
                }
                if(dataObj.position!==""){
                	
                }
                var dataArr=JSON.parse(dataObj.position);
                clearAll();
                var drawTestArr=[];
                $.each(dataArr,function(index,data){
                    drawTestArr.push(new BMap.Point(data.lng, data.lat));
                });
                
                drawTest=drawTestArr;
                positonParam=dataArr;
                //console.log(drawTest);
                //console.log(positonParam);
                preview(drawTestArr);
            }
        },
        error: function () {
            layer.msg("网络开小差啦", {icon: 2});
        }
    });
}
/*快递*/
$("#postType").on("change",function(){
    if($(this).val()==3){
        $("#nigtPrice").parent().css("display","none");
        $("#express").text("免运费金额");
        $("#dayPrice").attr("placeholder","请输入免运费金额...");
    }else{
        $("#nigtPrice").parent().css("display","block");
        $("#express").text("白天费用");
        $("#dayPrice").removeAttr("disabled");
        $("#dayPrice").attr("placeholder","请输入白天费用...");
    }
});
/*新增*/
$("#shop-print-add").on("click",function(){
    $("#sys-goods-list").collapse('close');
    clearAll();
    shop="insertShop";
    $("#mapBox").css("display","block");
    $("#dayPrice").val("");
    $("#name").val("");
    $("#nigtPrice").val("");
    $("#intro").val("");
});
/**
 * 图形装坐标点容器
 */
var drawTest = [];
/**
 * 创建百度地图对象
 */
var map = new BMap.Map('map');
/**
 * 禁止地图移动
 */
map.enableKeyboard();
/**
 * 设置中心位置的经纬度
 */
var poi = new BMap.Point(103.19667,31.06667);
/**
 * 设置默认显示级别
 */
map.centerAndZoom(poi, 11);
/**
 * 开启鼠标滑轮控制地图比例
 */
//map.enableScrollWheelZoom();
/**
 * 开启缩略菜单
 */
map.addControl(new BMap.NavigationControl());
var overlays = [];
var overlaycomplete = function (e) {
    overlays.push(e.overlay);
};

/**
 * 设置描绘样式
 */
var styleOptions = {
    strokeColor: "red",    //边线颜色。
    fillColor: "red",      //填充颜色。当参数为空时，圆形将没有填充效果。
    strokeWeight: 3,       //边线的宽度，以像素为单位。
    strokeOpacity: 0.8,	   //边线透明度，取值范围0 - 1。
    fillOpacity: 0.6,      //填充的透明度，取值范围0 - 1。
    strokeStyle: 'solid' //边线的样式，solid或dashed。
}

/**
 * 实例化鼠标绘制工具
 */
var drawingManager = new BMapLib.DrawingManager(map, {
    isOpen: true, //是否开启绘制模式
    enableDrawingTool: false, //是否显示工具栏
    drawingToolOptions: {
        anchor: BMAP_ANCHOR_TOP_RIGHT, //位置
        offset: new BMap.Size(3, 3), //偏离值
    },
    circleOptions: styleOptions, //圆的样式
    polylineOptions: styleOptions, //线的样式
    polygonOptions: styleOptions, //多边形的样式
    rectangleOptions: styleOptions //矩形的样式
});

/**
 * 添加鼠标绘制工具监听事件，用于获取绘制结果
 */
drawingManager.addEventListener('overlaycomplete', overlaycomplete);
function clearAll() {
    drawTest.splice(0,drawTest.length);
    positonParam.splice(0,positonParam.length);
    $("#position").val("");
    if(overlays.length > 0){
        for (var i = 0; i < overlays.length; i++) {
            map.removeOverlay(overlays[i]);
        }
        overlays.length = 0;
    }
}

/**
 *    添加地图点击事件监听
 *    每次点击收集好经纬度
 */

var positonParam = [];
map.addEventListener("click", function (e) {
    var dataObj = {};
    var longitudeValue = e.point.lng;
    var latitudeValue = e.point.lat;
    console.debug("当前点击处位置，经度为：" + longitudeValue + "，" + "纬度为：" + latitudeValue);
    drawTest.push(new BMap.Point(longitudeValue, latitudeValue));
    /*经纬度数据*/
    dataObj.lng = longitudeValue;
    dataObj.lat = latitudeValue;
    positonParam.push(dataObj);

});
/**
 * 创建地图搜索对象
 */
var localSearch = new BMap.LocalSearch(map);
/**
 * 允许自动调节窗体大小
 */
localSearch.enableAutoViewport();

/**
 * 根据地址名称获取经纬度
 * @returns
 */
function searchByStationName(address) {
    localSearch.setSearchCompleteCallback(function (searchResult) {
        var poi = searchResult.getPoi(0);
        //console.debug(poi.point.lng + "," + poi.point.lat);
    });
    localSearch.search();//模拟从数据库获得
}

/*
 * 预览
 */
function preview(text) {
    var dataArrStr = JSON.stringify(positonParam);
    $("#position").val(dataArrStr);
    if(typeof text=="object"){
        var polygon = new BMap.Polygon(text, {strokeColor: "red", strokeWeight: 2, strokeOpacity: 1, fillOpacity: 0});
    }else{
        var polygon = new BMap.Polygon(drawTest, {strokeColor: "red", strokeWeight: 2, strokeOpacity: 1, fillOpacity: 0});
    }
    map.addOverlay(polygon);
    overlays.push(polygon);
};


